package com.doctor.ui.homedoctor;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.doctor.adapter.DiseaseRecordAdapter;
import com.doctor.bean.DiseaseRecordBean;
import com.doctor.bean.PatientFileBean;
import com.doctor.comm.AlarmReceiver;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FragmentHelper;
import com.doctor.comm.MyApplication;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.database.DbOperator;
import com.doctor.net.ThreadPoolManager;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;
import com.doctor.view.NoScrollListView;

public class LookPatientFileFrag extends BaseFragment{

	/**
	 * 查看患者档案
	 */
	
	private Context context;
	private PatientFileBean patientFileBean;
	private String[] operation={"修改","删除","取消"};
	private NoScrollListView listView;
	private DiseaseRecordAdapter adapter;
	private LinearLayout addBtn;    //添加按钮
	private AddDiseaseRecordFrag addDiseaseRecordFrag;
	private ModifyDiseaseRecordFrag modifyDiseaseRecordFrag;
	private LookDiseaseRecordFrag lookDiseaseRecordFrag;
	private List<DiseaseRecordBean> beanList;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context=getActivity();
		patientFileBean=(PatientFileBean) getArguments().getSerializable(ConstConfig.BEAN);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.look_patient_file, container, false);
		initiaView(view);
		
		return view;
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
//		listView=null;
//		adapter=null;
//		beanList=null;
//		addDiseaseRecordFrag=null;
//		modifyDiseaseRecordFrag=null;
//		lookDiseaseRecordFrag=null;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		
		TextView number=(TextView) view.findViewById(R.id.number);
		number.setText(patientFileBean.getId()+"");
		
		TextView name=(TextView) view.findViewById(R.id.name);
		name.setText(patientFileBean.getName());
		
		TextView tvMarriage = (TextView) view.findViewById(R.id.marrige);
		String marriageText = patientFileBean.getMarriage();
		if (marriageText != null && "未婚".equals(marriageText.trim())) {
			tvMarriage.setText("未婚");
		} else if (marriageText != null && "已婚".equals(marriageText.trim())) {
			tvMarriage.setText("已婚");
		}
		
		TextView sex=(TextView) view.findViewById(R.id.sex);
		String sex_txt=patientFileBean.getSex();
		if (sex_txt!=null && "男".equals(sex_txt.trim())) {
			sex.setText("男");
		} else if (sex_txt!=null && "女".equals(sex_txt.trim())) {
			sex.setText("女");
		}
		
		TextView email=(TextView) view.findViewById(R.id.email);
		email.setText(patientFileBean.getEmail());
		
		TextView birthDay=(TextView) view.findViewById(R.id.birthday);
		birthDay.setText(patientFileBean.getBirthDay());
		
		TextView endDay=(TextView) view.findViewById(R.id.endday);
		endDay.setText(patientFileBean.getEndDay());
		
		TextView address=(TextView) view.findViewById(R.id.address);
		address.setText(patientFileBean.getAddress());
		
		TextView phone=(TextView) view.findViewById(R.id.phone);
		phone.setText(patientFileBean.getPhone());
		
		TextView mobile=(TextView) view.findViewById(R.id.mobile);
		mobile.setText(patientFileBean.getMobile());
		
		TextView body=(TextView) view.findViewById(R.id.body);
		body.setText(patientFileBean.getBody());
		
		TextView bloodType=(TextView) view.findViewById(R.id.bloodType);
		bloodType.setText(patientFileBean.getBloodType());
		
		TextView tvContacts = (TextView) view.findViewById(R.id.contacts);
		String contacts = patientFileBean.getContacts();
		if (contacts != null)
			tvContacts.setText(contacts);
		
		TextView tvContactsMobile = (TextView) view.findViewById(R.id.contacts_mobile);
		String contactsMobile = patientFileBean.getContactsMobile();
		if (contactsMobile != null)
			tvContactsMobile.setText(contactsMobile);
		
		TextView tvAllergy = (TextView) view.findViewById(R.id.allergy);
		String allergy = patientFileBean.getAllergy();
		if (allergy != null)
			tvAllergy.setText(allergy);
		
		TextView familyHistory=(TextView) view.findViewById(R.id.familyHistory);
		familyHistory.setText(patientFileBean.getFamilyHistory());
		
		TextView personalHistory=(TextView) view.findViewById(R.id.personalHistory);
		personalHistory.setText(patientFileBean.getPersonalHistory());
		
		TextView diseaseHistory=(TextView) view.findViewById(R.id.diseaseHistory);
		diseaseHistory.setText(patientFileBean.getDiseaseHistory());
		
		
		addBtn=(LinearLayout) view.findViewById(R.id.addBtn);
		addBtn.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View arg0) {
				addDiseaseRecordFrag=null;
				addDiseaseRecordFrag=new AddDiseaseRecordFrag();
				Bundle bundle=new Bundle();
				bundle.putInt(ConstConfig.ID, patientFileBean.getId());
				addDiseaseRecordFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, addDiseaseRecordFrag).addToBackStack(null).commit();
			}
		});
		listView=(NoScrollListView) view.findViewById(R.id.listView);
		
		beanList=new ArrayList<DiseaseRecordBean>();
		adapter=new DiseaseRecordAdapter(context,beanList);
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				final DiseaseRecordBean diseaseRecordBean=(DiseaseRecordBean) arg1.getTag(R.id.bean_tag);
				lookDiseaseRecordFrag=null;
				lookDiseaseRecordFrag=new LookDiseaseRecordFrag();
				Bundle bundle=new Bundle();
				bundle.putSerializable(ConstConfig.BEAN, diseaseRecordBean);
				bundle.putSerializable(ConstConfig.BEAN_2, patientFileBean);
				lookDiseaseRecordFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, lookDiseaseRecordFrag).addToBackStack(null).commit();
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				final DiseaseRecordBean diseaseRecordBean=(DiseaseRecordBean) arg1.getTag(R.id.bean_tag);
				
				final int beanPosition=arg2;
				
				DialogHelper.selectDialog(context, null, operation, new DialogSelectCallback() {
					@Override
					public void onDialogSelected(int position1) {
						// TODO Auto-generated method stub
						if (position1==0) {
							//修改
							modifyDiseaseRecordFrag=null;
							modifyDiseaseRecordFrag=new ModifyDiseaseRecordFrag();
							Bundle bundle=new Bundle();
							bundle.putSerializable(ConstConfig.BEAN, diseaseRecordBean);
							modifyDiseaseRecordFrag.setArguments(bundle);
							FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
							FragmentHelper.setFragSwitchAnimation(transaction);
							transaction.replace(R.id.frag_container, modifyDiseaseRecordFrag).addToBackStack(null).commit();
							
						} else if (position1==1) {
							DialogHelper.noticeDialog(context, "删除后不可恢复，确定要删除？", new NoticeDialogCallback() {								
								@Override
								public void onClicked(int position2) {
									// TODO Auto-generated method stub
									if (position2==1) {
										//删除
										int row=DbOperator.getInstance(context).deleteData(ConstConfig.DISEASE_RECORD_TABLE, diseaseRecordBean.getId());
										String deleteResult=row>0?"成功！":"失败！";
										Toast.makeText(context, "删除"+deleteResult, Toast.LENGTH_SHORT).show();
										if (row>0) {
											final int cid = adapter.getItem(beanPosition).getCid();
											final int id = adapter.getItem(beanPosition).getId();
											final int patientId = adapter.getItem(beanPosition).getPatientId();
											//更新adapter数据
											adapter.removeBean(beanPosition);
											if (diseaseRecordBean.getAlarmId()>9*ConstConfig.BASE_ID) {
												AlarmReceiver.cancelAlarm(getActivity(), diseaseRecordBean.getAlarmId());
											}
											if (cid > 0) {
												//记录到删除表里
												ThreadPoolManager.getInstance().addTask(new Runnable() {
													@Override
													public void run() {
														// TODO Auto-generated method stub
														ContentValues cv = new ContentValues();
														cv.put("_id", id);
														cv.put("_patient_id", patientId);
														cv.put("_cid", cid);
														DbOperator.getInstance(MyApplication.getInstance()).insertData(ConstConfig.DELETED_DISEASE_RECORD_TABLE, cv);
													}
												});
											}
										}
									}
								}
							});
						}
					}
				});
				return true;
			}
		});
		if (adapter!=null) {
			adapter.clear();
		}
		freshData();
	}
	
	
	private void freshData(){
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				final List<DiseaseRecordBean> list=DbOperator.getInstance(context).selectDiseaseRecordData(patientFileBean.getId());
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (list!=null && list.size()>0) {
							for (DiseaseRecordBean bean : list) {
								adapter.addBean(bean);
							}
							adapter.notifyDataSetChanged();
						}
						/**
						 * 设置ListView高度自适应
				         * ListView item必须是LinearLayout
						 * 其他的Layout(如RelativeLayout)没有重写onMeasure()，所以会在onMeasure()时抛出异常
						*/
						int height=0;
						for (int i = 0; i < adapter.getCount(); i++) {
							View listItem=adapter.getView(i, null, listView);
							listItem.measure(0, 0);
							height+=listItem.getMeasuredHeight();
						}
						ViewGroup.LayoutParams params=listView.getLayoutParams();
						params.height=height+(listView.getDividerHeight()*(adapter.getCount()-1));
						listView.setLayoutParams(params);
					}
				});
			}
		}.start();
	}
	
	
	
}
